import React from 'react';
import _ from 'underscore';
import { findDOMNode } from 'react-dom';

import View from 'lib/View.jsx';
import Card from 'lib/components/card.jsx';
import ItemSelect from 'lib/components/ItemSelect.jsx';
import TopBar from 'lib/components/TopbarWidget.jsx';
import dispatcher from 'lib/dispatcher';
import AutoComplete from 'lib/components/AutoComplete.jsx';

import Layout from '../common/layout.jsx';
import Scope from './MainScope.es6';

export default class MainView extends View {
  constructor(props, context) {
    super(props, context)
    this.state.searchBoxShow = false
    this.onSortChange = this.onSortChange.bind(this)
    this.toggleSearchBox = this.toggleSearchBox.bind(this)
    this.navigateTransaction = this.navigateTransaction.bind(this)
  }
  onSortChange(key) {
    dispatcher.dispatch({
      $type:'CHANGESORT',
      key:key
    })
  }
  toggleSearchBox() {
    dispatcher.dispatch({
      $type: 'toggle_searchbox',
      show: !this.state.searchBoxShow,
      callback: () => $(findDOMNode(this.refs.autoComplete)).find('input[type=text]').focus()
    });
  }
  searchURL(input,options) {
    return $.ajax({
      url:BlueWare.urlPrefix + '/app/' + BlueWare.appId + '/searchurl.json',
      data:{
        input:input,
        force:options.source === 'enter'
      }
    })
  }

  parseFnHandler(data) {
    return _.map(data, item => ({
      group: item.name,
      value: item.id,
      domainId: item.id,
      options: _.map(item.urls, p => ({
        value: `${ item.id }/url/${ p.id }`,
        id: p.id,
        label: p.name,
        domainId: item.id
      }))
    }));
  } // parseFnHandler

  navigateTransaction(item) {
    if (item&&item.value) {
      dispatcher.dispatch({
        $type: 'search_info',
        show: true,
        domainId: item.domainId,
        id: item.id,
        callback: () => this.props.history.pushState(null, '/domain/'+item.value)
      });
    }
  }

  render() {
    return (
      <Layout title="请求" subtitle="展现外部请求性能">
        <div className="float-position-relative">
          <div className="pure-g">
            <div className="pure-u-1 pure-u-xl-1-3">
              <div className="box">
                <Card>
                  <div className="float-right">
                    <div className="search-container" onClick={ this.toggleSearchBox }>
                      <div className="text">搜索</div>
                      <i className="iconfont">&#xe66d;</i>
                    </div>
                  </div>
                  <ItemSelect options={this.state.sortOptions} onChange={this.onSortChange} />
                  {
                    this.state.searchBoxShow?(
                      <div style={{marginBottom: '10px'}}>
                        <AutoComplete
                          ref="autoComplete"
                          placeholder="domain/path 或 /path"
                          className="input-text"
                          promiseFn={this.searchURL}
                          parseFn={ this.parseFnHandler }
                          onComplete={this.navigateTransaction}
                          enterSearch={false}
                          limitSymbolLength={ 0 } />
                        {
                          this.state.searchBoxShow && !this.state.searchTopbar.none
                            ? (
                              this.state.searchTopbar.data && !this.state.searchTopbar.data.length
                                ? (
                                  <ul className="handle-list" style={{ marginTop: 5 }}>
                                    <li>
                                      <div className="handle" style={{
                                        backgroundColor: '#fff',
                                        color: '#666',
                                        cursor: 'default'
                                      }}>
                                        <div className="bar-text">
                                          <span
                                            className="name"
                                            style={{
                                              width: '100%',
                                              textAlign: 'center'
                                            }}>暂无数据</span>
                                        </div>
                                      </div>
                                    </li>
                                  </ul>
                                ) : (
                                  <div>
                                    <TopBar
                                      style={{ marginTop: 5 }}
                                      store={ this.state.searchTopbar } />
                                  </div>
                                )
                            ) : null
                        }
                        <div style={{ borderTop: '1px solid #8697AF', margin: '12px auto' }}></div>
                      </div>
                    ):null
                  }
                  <TopBar store={this.state.topbar} asyncLoad={ !(this.state.searchBoxShow && !this.state.searchTopbar.none) } />
                  {
                    this.state.topbar.data && this.state.topbar.data.length
                      ? (
                        <div style={{
                          color: '#D7D7D7',
                          marginTop: '10px'
                        }}>
                          默认展示 Top 20 的数据，通过搜索可以展示更多数据。
                        </div>
                      ) : null
                  }
                </Card>
              </div>
            </div>
            <div className="pure-u-1 pure-u-xl-2-3">
              { React.cloneElement(this.props.children, { routeParams: this.props.params, key: this.getHandlerKey() }) }
            </div>
          </div>
        </div>
      </Layout>
    )
  }
}
MainView.defaultProps = {
  Scope:Scope
}
